package com.example.its2021606134chh.MyCarModule;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.ETCModule.ETC_Car_Balance;
import com.example.its2021606134chh.ETCModule.ETC_Car_Recharge;
import com.example.its2021606134chh.ETCModule.MySQLiteOpenHelper;
import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.LoginModule.LoginActivity;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MC_balanceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MC_balanceFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private MyCarShow myCarShowNum1;
    private MyCarShow myCarShowNum2;
    private MyCarShow myCarShowNum3;
    private MyCarShow myCarShowNum5;
    private int BalAlaNum;
    private int[] carList = {1, 2, 3, 4};   //车辆列表
    private static final int CAR1 = 1;
    private static final int CAR2 = 2;
    private static final int CAR3 = 3;
    private static final int CAR4 = 4;
    private int carBalance1;
    private int carBalance2;
    private int carBalance3;
    private int carBalance4;

    MySQLiteOpenHelper openHelper;
    SQLiteDatabase database;

    public MC_balanceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MC_balanceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MC_balanceFragment newInstance(String param1, String param2) {
        MC_balanceFragment fragment = new MC_balanceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_m_c_balance, container, false);
        myCarShowNum1 = (MyCarShow) view.findViewById(R.id.myCarShowNum1);
        myCarShowNum2 = (MyCarShow) view.findViewById(R.id.myCarShowNum2);
        myCarShowNum3 = (MyCarShow) view.findViewById(R.id.myCarShowNum3);
        myCarShowNum5 = (MyCarShow) view.findViewById(R.id.myCarShowNum5);

//        从SharedPreferences取出告警阈值
        SharedPreferences sp = getActivity().getSharedPreferences("balance_alarm", Activity.MODE_PRIVATE);
        if (sp != null) {
            BalAlaNum = sp.getInt("BalAlaNum", 0);
        }

//                使用Timers和TimerTask异步实现车辆余额动态获取与设置
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                for (int carId : carList) {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
                            ETC_Car_Balance carBalance = gson.fromJson(json, ETC_Car_Balance.class);
                            String sCarBal = String.valueOf(carBalance.getBalance());

//                            根据车号设置阈值提示
                            if (carId == CAR1) {
                                myCarShowNum1.setText2(BalAlaNum, sCarBal);
                                myCarShowNum1.invalidate();
                                carBalance1 = carBalance.getBalance();
                            } else if (carId == CAR2) {
                                myCarShowNum2.setText2(BalAlaNum, sCarBal);
                                myCarShowNum2.invalidate();
                                carBalance2 = carBalance.getBalance();
                            } else if (carId == CAR3) {
                                myCarShowNum3.setText2(BalAlaNum, sCarBal);
                                myCarShowNum3.invalidate();
                                carBalance3 = carBalance.getBalance();
                            } else if (carId == CAR4) {
                                myCarShowNum5.setText2(BalAlaNum, sCarBal);
                                myCarShowNum5.invalidate();
                                carBalance4 = carBalance.getBalance();
                            }
                        }
                    }, "get_car_account_balance", new String[]{"CarId", "UserName"}, carId, "user1");
                }
            }
        };
        timer.schedule(timerTask, 0, 5000);

//                取得当前时间
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
        String sNow = ft.format(dNow);

//        根据点击事件实现小车充值功能
        myCarShowNum1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogueBox(CAR1, carBalance1, sNow);
            }
        });
        myCarShowNum2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogueBox(CAR2, carBalance2, sNow);
            }
        });
        myCarShowNum3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogueBox(CAR3, carBalance3, sNow);
            }
        });
        myCarShowNum5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogueBox(CAR4, carBalance4, sNow);
            }
        });
        return view;
    }

//    我的充值对话框
    private void dialogueBox(int carID, int carBalance, String time) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(Objects.requireNonNull(getActivity()).getBaseContext()).inflate(R.layout.activity_recharge_dialog,null,false);
        dialog.setView(view);
        Button btnRechargeSave = (Button)view.findViewById(R.id.btnRechargeSave);
        EditText edtRechargeNum = (EditText)view.findViewById(R.id.edtRechargeNum);
        Button btnRechargeCancel = (Button)view.findViewById(R.id.btnRechargeCancel);
        AlertDialog mdialog = dialog.show();
        btnRechargeSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                取得充值金额
                String sRecharge = edtRechargeNum.getText().toString();
                int rechargeNum = Integer.parseInt(sRecharge);
//                判断1到50的整数
                if (rechargeNum >= 1 &&  rechargeNum <= 50) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                @Override
                                public void onFailure(Exception e) {

                                }

                                @Override
                                public void onResponse(String json) {
                                    String msg = "";
                                    Log.i("TAG", json);
                                    Gson gson = new Gson();
                                    ETC_Car_Recharge car_recharge = gson.fromJson(json, ETC_Car_Recharge.class);
                                    String RESULT = car_recharge.getRESULT();
                                    if (RESULT.equals("S")) {
//                                        向数据库传入数据
                                        ContentValues values = new ContentValues();
                                        values.put("carID", carID);
                                        values.put("carBalance", carBalance + rechargeNum);
                                        values.put("carRecharge",rechargeNum);
                                        values.put("user", "user1");
                                        values.put("time", time);
                                        openHelper = new MySQLiteOpenHelper(getContext(), "ETCaccount1.db", null, 1);
                                        database = openHelper.getWritableDatabase();
                                        database.insert("etccar", null, values);
                                        database.close();
                                        mdialog.dismiss();
                                        msg = carID + "号小车充值" + rechargeNum + "元成功";
                                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                    } else {
                                        mdialog.dismiss();
                                        msg = carID + "号小车充值失败";
                                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }, "set_car_account_recharge", new String[]{"CarId", "Money", "UserName"}, carID, rechargeNum, "user1");
                        }
                    }).start();
                } else {
                    Toast.makeText(getActivity(), "只能输入1到50之间的整数", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnRechargeCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mdialog.dismiss();
            }
        });
    }


}